require 'net/http'
require 'rubygems'
require 'xmlsimple'

class BigHugeThesaurusHelper

  NOUN = 'noun'
  VERB = 'verb'
  ADJETIVE = 'adjetive'
  ADVERB = 'adverb'

  TARGET_URL = "http://words.bighugelabs.com/api/2/4d5fc73b3731456916e8476a21180a82/word/xml"
  
  def self.look_up(word)
    begin
      response = Net::HTTP::Proxy(APP_CONFIG[:proxy_addr], APP_CONFIG[:proxy_port]).get_response(URI.parse(TARGET_URL.sub('/word/', "/#{word.text}/")))
    rescue
      response = nil
    end

    if response
      if response.instance_of?(Net::HTTPOK)
        res = BigHugeThesaurusHelper.parse_xml(response.body)
        word.add_related_terms(res) if !res.empty? && word.save
      end

      if response.instance_of?(Net::HTTPSeeOther)
        return BigHugeThesaurusHelper.see_other(response.message)
      end
    end
  end

  private

  # "syn" for synonyms, "ant" for antonyms,
  # "rel" for related terms, "sim" for similar terms
  def self.parse_xml(xml)
    return {} if xml.blank?

    xml_data = XmlSimple.xml_in(xml)
    words = {:syn => [], :ant => [], :rel => [], :sim => []}

    xml_data.values.first.each do |hash|
      word = Word.find_or_create_by_text(hash['content'].downcase)
      words[hash['r'].to_sym] << word
    end

    words.delete_if { |key, value| value.empty? }
  end

  def self.see_other(text)
    Word.find_or_create_by_text(text.downcase)
  end
  
end
